package api

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

const (
	// 基金API基础URL
	FundAPIBaseURL = "https://api.autostock.cn/v1"
)

// FundDetailResponse 基金详情接口响应结构
type FundDetailResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	TraceId string      `json:"traceId"`
	Data    FundDetail  `json:"data"`
	Meta    interface{} `json:"meta"`
}

// FundDetail 基金详情数据结构
type FundDetail struct {
	Code                     string        `json:"code"`
	Name                     string        `json:"name"`
	Type                     string        `json:"type"`
	NetWorth                 float64       `json:"netWorth"`
	ExpectWorth              float64       `json:"expectWorth"`
	TotalWorth               float64       `json:"totalWorth"`
	ExpectGrowth             string        `json:"expectGrowth"`
	DayGrowth                string        `json:"dayGrowth"`
	LastWeekGrowth           string        `json:"lastWeekGrowth"`
	LastMonthGrowth          string        `json:"lastMonthGrowth"`
	LastThreeMonthsGrowth    string        `json:"lastThreeMonthsGrowth"`
	LastSixMonthsGrowth      string        `json:"lastSixMonthsGrowth"`
	LastYearGrowth           string        `json:"lastYearGrowth"`
	BuyMin                   string        `json:"buyMin"`
	BuySourceRate            string        `json:"buySourceRate"`
	BuyRate                  string        `json:"buyRate"`
	Manager                  string        `json:"manager"`
	FundScale                string        `json:"fundScale"`
	NetWorthDate             string        `json:"netWorthDate"`
	ExpectWorthDate          string        `json:"expectWorthDate"`
	NetWorthData             [][]string    `json:"netWorthData"`
	TotalNetWorthData        [][]string    `json:"totalNetWorthData"`
	MillionCopiesIncome      float64       `json:"millionCopiesIncome"`
	MillionCopiesIncomeData  [][]string    `json:"millionCopiesIncomeData"`
	MillionCopiesIncomeDate  string        `json:"millionCopiesIncomeDate"`
	SevenDaysYearIncome      float64       `json:"sevenDaysYearIncome"`
	SevenDaysYearIncomeData  [][]string    `json:"sevenDaysYearIncomeData"`
	FundType                 string        `json:"fundType"`
	ThisYearGrowth           string        `json:"thisYearGrowth"`
	RequestFail              int           `json:"requestFail"`
	ResolveFail              int           `json:"resolveFail"`
}

// GetFundDetail 获取基金详情
func GetFundDetail(code string, startDate string) (*FundDetail, error) {
	// 构建请求URL
	url := fmt.Sprintf("%s/fund/detail?code=%s", FundAPIBaseURL, code)
	if startDate != "" {
		url = fmt.Sprintf("%s&startDate=%s", url, startDate)
	}

	// 创建HTTP客户端并设置超时
	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	// 发起HTTP请求
	resp, err := client.Get(url)
	if err != nil {
		return nil, fmt.Errorf("请求基金详情失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应内容失败: %v", err)
	}

	// 解析响应JSON
	var response FundDetailResponse
	if err := json.Unmarshal(body, &response); err != nil {
		return nil, fmt.Errorf("解析JSON失败: %v", err)
	}

	// 检查响应状态码
	if response.Code != 0 && response.Code != 200 {
		return nil, fmt.Errorf("API请求失败: %s", response.Message)
	}

	return &response.Data, nil
}

// GetFundPerformanceFromDetail 从基金详情提取性能数据
func GetFundPerformanceFromDetail(fundDetail *FundDetail) *FundPerformance {
	// 计算最大回撤和波动率
	maxDrawdown := 0.0
	volatility := 0.0

	// 计算增长率数据
	weekGrowth := parseGrowthRate(fundDetail.LastWeekGrowth)
	monthGrowth := parseGrowthRate(fundDetail.LastMonthGrowth)
	threeMonthGrowth := parseGrowthRate(fundDetail.LastThreeMonthsGrowth)
	sixMonthGrowth := parseGrowthRate(fundDetail.LastSixMonthsGrowth)
	yearGrowth := parseGrowthRate(fundDetail.LastYearGrowth)

	// 从净值数据计算波动率和最大回撤
	if len(fundDetail.NetWorthData) > 30 {
		volatility, maxDrawdown = calculateVolatilityAndDrawdown(fundDetail.NetWorthData)
	}

	// 计算夏普比率（简化计算，这里假设无风险利率为3%）
	sharpRatio := 0.0
	if volatility > 0 {
		sharpRatio = (yearGrowth - 0.03) / volatility
	}

	return &FundPerformance{
		WeekReturn:  weekGrowth,
		MonthReturn: monthGrowth,
		ThreeMonth:  threeMonthGrowth,
		SixMonth:    sixMonthGrowth,
		YearReturn:  yearGrowth,
		ThreeYear:   threeMonthGrowth * 4, // 简化计算，实际应该使用3年数据
		FiveYear:    threeMonthGrowth * 6.5, // 简化计算，实际应该使用5年数据
		FromStart:   yearGrowth * 3, // 简化计算，实际应该计算从成立至今
		MaxDrawdown: maxDrawdown,
		Volatility:  volatility,
		SharpRatio:  sharpRatio,
	}
}

// 计算波动率和最大回撤
func calculateVolatilityAndDrawdown(netWorthData [][]string) (float64, float64) {
	// 简化计算逻辑
	var growthRates []float64
	maxDrawdown := 0.0
	maxValue := 0.0

	for _, data := range netWorthData {
		if len(data) >= 3 {
			// 解析单位净值和增长率
			netWorth := parseGrowthRate(data[1])
			growthRate := parseGrowthRate(data[2])
			
			// 添加到增长率列表
			growthRates = append(growthRates, growthRate)
			
			// 计算最大回撤
			if netWorth > maxValue {
				maxValue = netWorth
			} else if maxValue > 0 {
				drawdown := (maxValue - netWorth) / maxValue
				if drawdown > maxDrawdown {
					maxDrawdown = drawdown
				}
			}
		}
	}

	// 计算波动率（日增长率的标准差）
	volatility := calculateStandardDeviation(growthRates)
	
	// 年化处理（假设252个交易日）
	volatility = volatility * 15.87 // sqrt(252)

	return volatility, maxDrawdown
}

// 计算标准差
func calculateStandardDeviation(values []float64) float64 {
	if len(values) == 0 {
		return 0
	}

	// 计算平均值
	sum := 0.0
	for _, v := range values {
		sum += v
	}
	mean := sum / float64(len(values))

	// 计算方差
	variance := 0.0
	for _, v := range values {
		variance += (v - mean) * (v - mean)
	}
	variance = variance / float64(len(values))

	// 计算标准差
	return variance / float64(len(values))
}

// 解析增长率字符串为float64
func parseGrowthRate(rateStr string) float64 {
	var rate float64
	fmt.Sscanf(rateStr, "%f%%", &rate)
	return rate / 100.0
} 